package com.le.high.class4;

import org.junit.Test;

/**
 * 给定一个字符串str，求最长的回文子序列。注意区分子序列和子串的不同
 * 逆序求最长公共子序列
 */
public class Problem02_PalindromeSubsequence {

    public static String maxLen1(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        char[] s1 = str.toCharArray();
        char[] s2 = reverse(s1);
        int[][] dp = getDp(s1, s2);
        int m = s1.length - 1;
        int n = s2.length - 1;
        System.out.println(dp[m][n]);
        char[] res = new char[dp[m][n]];
        int index = res.length - 1;
        while (index >= 0) {
            // 判断当前值是否和左边的值相等
            if (n > 0 && dp[m][n] == dp[m][n - 1]) {
                n--;
                // 判断当前值是否和上边的值相等
            } else if (m > 0 && dp[m][n] == dp[m - 1][n]) {
                m--;
            } else {
                res[index--] = s1[m];
                m--;
                n--;
            }
        }
        return String.valueOf(res);
    }

    public static char[] reverse(char[] s) {
        char[] res = new char[s.length];
        for (int i = 0; i < s.length; i++) {
            res[i] = s[s.length - 1 - i];
        }
        return res;
    }

    public static int[][] getDp(char[] str1, char[] str2) {
        int[][] dp = new int[str1.length][str2.length];
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        for (int i = 1; i < str1.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], str1[i] == str2[0] ? 1 : 0);
        }
        for (int i = 1; i < str2.length; i++) {
            dp[0][i] = Math.max(dp[0][i - 1], str1[0] == str2[i] ? 1 : 0);
        }
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                if (str1[i] == str2[j]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
                }
            }
        }
        return dp;
    }

    @Test
    public void test(){
        String test = "A1BC2D33FG2H1I";
        System.out.println(maxLen1(test));
    }
}
